package com.zh.kotlin_mvvm.ftp.utils;


import android.text.TextUtils;


import com.blankj.utilcode.util.GsonUtils;
import com.google.gson.JsonSyntaxException;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GsonUtil {

    public static String objectToJson(Object object) {
        return GsonUtils.toJson(object);
    }

    /**
     * 将jsonStr转换成cl对象
     *
     * @param jsonStr
     * @return
     */
    public static <T extends Object> T jsonToBean(String jsonStr, Class<?> cl) {
        Object obj = null;
        if (!TextUtils.isEmpty(jsonStr))
            obj = GsonUtils.fromJson(jsonStr, cl);
        return (T) obj;
    }

    public static <T> T jsonToObject(String buffer, Class<T> cls) {
        if (null == buffer || cls == null)
            return null;
        T t;
        try {
            t = GsonUtils.fromJson(buffer, cls);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return null;
        }
        return t;
    }


    public static String mapToJson(Map src) {
        String jsonResult = GsonUtils.toJson(src);
        return jsonResult;
    }

    public static Map jsonToMap(String jsString) {
        Map map = new HashMap();
        map = GsonUtils.fromJson(jsString, Map.class);
        return map;
    }

    /**
     * 返回cla 类型的list数组
     *
     * @param s
     * @param cla
     * @return
     */
    public static <T extends Object> T jsonToBeanList(String s, Class<?> cla) {

        List<Object> ls = new ArrayList<Object>();
        JSONArray ss;
        try {
            ss = new JSONArray(s);
            for (int i = 0; i < ss.length(); i++) {
                String str = ss.getString(i);
                Object a = jsonToBean(str, cla);
                ls.add(a);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return (T) ls;
    }

    public static String beanToJson(Object bean) {
        return GsonUtils.toJson(bean);
    }
}
